<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC02
 * Date: 10/10/13
 * Time: 2:30 PM
 * To change this template use File | Settings | File Templates.
 */

class ChangePasswordForm extends CFormModel {
    public $userId;
    public $oldPassword;
    public $password;
    public $passwordRepeat;

    public function rules() {
        return array(
            array('oldPassword, password, passwordRepeat','required'),
            array('oldPassword, password, passwordRepeat','length', 'max' => 32),
            array('oldPassword', 'validPassword'),
            array('password', 'compare', 'compareAttribute' => 'passwordRepeat'),
            array('passwordRepeat', 'safe')
        );
    }

    public function validPassword() {
        $user = $this->getUser();
        if (!$user->validatePassword($this->oldPassword))
            $this->addError('oldPassword', 'Old password is wrong');
    }

    public function changePassword() {
        //change pass
        $user = $this->getUser();

        $user->password = User::model()->hashPassword($this->password);

        return $user->save();
    }

    public function getUser() {
        return User::model()->findByPk($this->userId);
    }
}